import 'dart:async';

import 'package:flutter/material.dart';
import 'package:moose_app/ui/values/values.dart';

import 'auth_text_field_wrap.dart';

class ATHAuthSendSmsInput extends StatefulWidget {
  final String hintText;
  final ValueChanged<String> onChanged;
  final TextEditingController controller;

  const ATHAuthSendSmsInput({
    Key key,
    this.hintText,
    this.controller,
    this.onChanged,
  }) : super(key: key);

  @override
  _SendSmsCodeFieldState createState() => _SendSmsCodeFieldState();
}

class _SendSmsCodeFieldState extends State<ATHAuthSendSmsInput> {
  static const duration = const Duration(seconds: 1);

  int _countdownTime = 0;

  bool isSendSmsCode = false;

  Timer _timer;

  void sendSmsCode() {
    _countdownTime = 5;
    setState(() {
      isSendSmsCode = true;
    });
    _timer = Timer.periodic(duration, (Timer t) {
      _countdownTime--;

      setState(() {
        _countdownTime = _countdownTime;
      });

      if (_countdownTime <= 0) {
        if (_timer != null) _timer.cancel();
        setState(() {
          isSendSmsCode = false;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ATHAuthTextFieldWrap(
      child: Row(
        children: <Widget>[
          Expanded(
            child: TextField(
              onChanged: widget.onChanged,
              controller: widget.controller,
              decoration: InputDecoration(
                hintText: widget.hintText,
                icon: Container(
                  padding: EdgeInsets.only(left: kSize16),
                  child: Icon(
                    Icons.message,
                    color: kColorPrimary,
                  ),
                ),
                border: InputBorder.none,
              ),
            ),
          ),
          Container(
              padding: EdgeInsets.symmetric(horizontal: kSize16),
              child: isSendSmsCode
                  ? Text('$_countdownTime s')
                  : GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: sendSmsCode,
                      child: Icon(
                        Icons.send,
                        color: kColorPrimary,
                      ),
                    ))
        ],
      ),
    );
  }

  @override
  void dispose() {
    if (_timer != null) _timer.cancel();
    super.dispose();
  }
}
